#define  _CRT_SECURE_NO_WARNINGS 1
#include "stack.h"

void StackInit(Stack* ps)
{
	assert(ps);

	ps->a = NULL;
	ps->capacity = ps->size = 0;
}

void StackDestory(Stack* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->size = 0;
}

static void StackCheckCapacity(Stack* ps)
{
	if (ps->capacity == ps->size)
	{
		int newcapacity = ps->capacity == 0 ? 5 : 2 * ps->capacity;
		SDataType* pn = (SDataType*)realloc(ps->a, sizeof(SDataType) * newcapacity);
		if (!pn)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		ps->a = pn;
		ps->capacity = newcapacity;
	}
}

void StackPush(Stack* ps, SDataType x)
{
	assert(ps);

	StackCheckCapacity(ps);

	ps->a[ps->size] = x;
	ps->size++;
}

void StackPop(Stack* ps)
{
	assert(ps);
	assert(ps->size > 0);

	ps->size--;
}

SDataType StackTop(Stack* ps)
{
	assert(ps);
	assert(ps->size > 0);

	return ps->a[ps->size - 1];
}

bool StackEmpty(Stack* ps)
{
	assert(ps);

	return ps->size == 0;
}

int StackSize(Stack* ps)
{
	assert(ps);

	return ps->size;
}